package com.simple.datax.transport.webservice.processor;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.sql.DataSource;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

/**
 * WebService 具体业务实现类
 * @author Jin Yi
 *
 */
public class WebServiceProcessor {
	private static final Logger logger = Logger.getLogger(WebServiceProcessor.class);
	private static final String[] EXTENSION = {"xml"};
	private DataSource dataSource;
	private static final int RECV_IN = 1;
	private static final int SEND_OUT = 2;
	private static final String encoding = "utf-8";
	
	/**
	 * 企业验证
	 * @param user
	 * @param password
	 * @return
	 */
	public boolean validate(String user, String password) {
		// TODO: implements real validation
//		logger.debug("WebServiceProcessor Object: " + this);
		return true;
	}
	
	/**
	 * 保存报文至企业的FTP目录中
	 * @param filePathName
	 * @return
	 */
	public boolean saveMessageFile(String user, String content) {
		try {
			String path = getLocalPath(user, RECV_IN);
			if (path == null) {
				return false;
			}
			String filePathName = user + "_" + UUID.randomUUID().toString() + ".xml";
			File outputFile = new File(path + File.separator + filePathName);
			FileUtils.writeByteArrayToFile(outputFile, content.getBytes(encoding));
			return true;
		} catch (Exception ex) {
			logger.error("Backup message file failed.", ex);
		}
		return false;
	}
	
	public List<String> getDataList(String entId) throws Exception {
		List<String> ret = new ArrayList<String>();
//		try {
			String path = getLocalPath(entId, SEND_OUT);
			if (path == null) {
				throw new Exception("Not found Local Path for " + entId);
//				return ret;
			}
			File pathFile = new File(path);
			if (!pathFile.exists()) {
				pathFile.mkdirs();
			}
			@SuppressWarnings("unchecked")
			Collection<File> files = FileUtils.listFiles(new File(path), EXTENSION, false);
	
			//迭代输出
	        for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
	            File file = iterator.next();
	            ret.add(file.getName());
	        }
//		} catch (Exception ex) {
//			logger.error("getDataList error", ex);
//		}
		return ret;
	}

	public byte[] getData(String entId, String messageId) throws Exception {
		String path = getLocalPath(entId, SEND_OUT);
		if (path == null) {
			if (path == null) {
				throw new Exception("Not found Local Path for " + entId);
//				return ret;
			}
		}
		File file = new File(path + File.separator + messageId);
//		try {
			byte[] ret = FileUtils.readFileToByteArray(file);
			if (!FileUtils.deleteQuietly(file)) {
				logger.warn("Failed to delete file:" + file.getAbsolutePath());
			}
			return ret;
//		} catch (IOException e) {
//			logger.error("Failed to read file:" + file.getAbsolutePath(), e);
//		}
//		return null;
	}
	
	private String getLocalPath(String entId, int inOrOutDir) {
		String ret = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs =  null;
		try {
			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement("SELECT LOCAL_IN_DIR, LOCAL_OUT_DIR FROM TBL_WS_PROP WHERE E_CODE=?");
			pstmt.setString(1, entId);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				ret = rs.getString(inOrOutDir);
				// 如果ret为空串，设置其为null，以便后续程序容易判断
				if (ret != null && ret.trim().isEmpty()) {
					ret = null;
				}
				logger.debug("get local path: " + ret);
			} else {
				logger.error("Not found Local Path for enterprise - "+ entId);
			}
		} catch (SQLException e) {
			logger.error("Failed to get Local Path for enterprise - "+ entId + e.toString());
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
			if (pstmt != null) {
				try {
					pstmt.close();
				} catch (SQLException e) {
				}
			}
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
				}
			}
		}
		return ret;
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
}
